package com.qtjf.qtmoneyservice.activity;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.qtjf.qtmoneyservice.R;
import com.qtjf.qtmoneyservice.constantSet.Constant;
import com.qtjf.qtmoneyservice.view.CameraPreview;
import com.qtjf.qtmoneyservice.view.MySurfaceView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

public class FirstActivity extends BaseActivity {

    Camera mCamera;
    private CameraPreview mPreview;
    ImageView img;
    Camera.PreviewCallback previewCallback;
    private Camera.AutoFocusCallback myAutoFocusCallback = null;
    FrameLayout preview;
    int width=0;
    int height=0;
    float scale=0;

    View saomiaoView;

    //其中 mCameraId 是当前使用的 CameraId, 一般前置为1， 后置为 0。

    Handler handler=new Handler(){
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            if(msg.arg1==1000)
            {
                try {
                    mCamera.setOneShotPreviewCallback(previewCallback);
                }catch (Exception e)
                {}

            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layout);
        super.setTranslucent();
        WindowManager wm = this.getWindowManager();

        //后面转移到启动页
        width=wm.getDefaultDisplay().getWidth();
        height=wm.getDefaultDisplay().getHeight();
        scale=this.getResources().getDisplayMetrics().density;
        initView();
        initData();
        initEvent();
    }



    private void initView() {
        preview= (FrameLayout) findViewById(R.id.camera_preview);
        saomiaoView= (View) findViewById(R.id.saomiao_view);

        mCamera = getCameraInstance();
        setParams(mCamera);
        try {
            setCameraDisplayOrientation(FirstActivity.this,0,mCamera);
        }catch (Exception e)
        {}


        // Create our Preview view and set it as the content of our activity.
        mPreview = new CameraPreview(this, mCamera);
        preview.addView(mPreview);
        img= (ImageView) findViewById(R.id.img);


        TranslateAnimation animation=new TranslateAnimation(0,0,height/2-120,height/2+120);
        animation.setDuration(1500);
        animation.setRepeatMode(Animation.REVERSE);//设置反方向执行
        animation.setRepeatCount(500);
        saomiaoView.setAnimation(animation);
        animation.start();
        myAutoFocusCallback = new Camera.AutoFocusCallback() {

            public void onAutoFocus(boolean success, Camera camera) {
                // TODO Auto-generated method stub
                if(success)//success表示对焦成功
                {
                    Log.i("success", "myAutoFocusCallback: success...");
                    //myCamera.setOneShotPreviewCallback(null);
                }
                else
                {
                    //未对焦成功
                    Log.i("success", "myAutoFocusCallback: 失败了...");
                }


            }
        };

        previewCallback=new Camera.PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] bytes, Camera camera) {
                //Toast.makeText(TestActivity.this,"11",Toast.LENGTH_SHORT).show();
                Bitmap bitmap=byte2bitmap(bytes,camera);
                img.setImageBitmap(bitmap);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(5000);
                            try {
                                mCamera.autoFocus(myAutoFocusCallback);//调自动对角
                            }catch (Exception e)
                            {}
                            Message msg=Message.obtain();
                            msg.arg1=1000;
                            handler.sendMessage(msg);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        };

    }


    private void initData() {
    }


    private void initEvent() {
/*
        mCamera.setOneShotPreviewCallback(new Camera.PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] bytes, Camera camera) {
                //Toast.makeText(TestActivity.this,"11",Toast.LENGTH_SHORT).show();
                Bitmap bitmap=byte2bitmap(bytes,camera);
                img.setImageBitmap(bitmap);*/
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                    try {
                        mCamera.autoFocus(myAutoFocusCallback);//调自动对角
                    }catch (Exception e)
                    {}
                    Message msg=Message.obtain();
                    msg.arg1=1000;
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
         /*   }
        });*/
    }



    //设置属性
    private void setParams(Camera mCamera)
    {
        try {
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setPictureFormat(PixelFormat.JPEG); //Sets the image format for picture 设定相片格式为JPEG，默认为NV21
            parameters.setPreviewFormat(PixelFormat.YCbCr_420_SP);
            // 设置拍照和预览图片大小
            int size=(int) (width-125*scale);

            Camera.Size preSize = getCloselyPreSize(true,width,height, parameters.getSupportedPreviewSizes());
            RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) preview.getLayoutParams();
            params.height=(int) (width-80*scale);
            params.width=(int) ((width-80*scale)/(preSize.width/(float)preSize.height));
            preview.setLayoutParams(params);
            parameters.setPictureSize(preSize.height,preSize.width); //指定拍照图片的大小
            parameters.setPreviewSize(preSize.height, preSize.width); // 指定preview的大小
            Log.d("pre",preSize.width+"   "+preSize.height+"   "+(int) ((width-80*scale)/(preSize.width/(float)preSize.height)));
            //这两个属性 如果这两个属性设置的和真实手机的不一样时，就会报错
            // 横竖屏镜头自动调整
            if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE)
            {
                parameters.set("orientation", "portrait"); //
                parameters.set("rotation", 90); // 镜头角度转90度（默认摄像头是横拍）
                mCamera.setDisplayOrientation(90); // 在2.2以上可以使用
            } else// 如果是横屏
            {
                parameters.set("orientation", "landscape"); //
                mCamera.setDisplayOrientation(0); // 在2.2以上可以使用
                // 设定配置参数并开启预览
                mCamera.setParameters(parameters); // 将Camera.Parameters设定予Camera
                mCamera.startPreview(); // 打开预览画面
            }
        }catch (Exception e)
        {

        }

        // parameters.setFlashMode("off"); // 无闪光灯

    }
/*
    //检测相机
    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }*/


    //访问相机
    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(1); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }



    private Bitmap byte2bitmap(byte[] bytes, Camera camera) {
        Bitmap bitmap = null;

        Camera.Size size = camera.getParameters().getPreviewSize(); // 获取预览大小
        final int w = size.width; // 宽度
        final int h = size.height;
        final YuvImage image = new YuvImage(bytes, ImageFormat.NV21, w, h,
                null);
        ByteArrayOutputStream os = new ByteArrayOutputStream(bytes.length);
        if (!image.compressToJpeg(new Rect(0, 0, w, h), 100, os)) {
            return null;
        }
        byte[] tmp = os.toByteArray();
        bitmap = BitmapFactory.decodeByteArray(tmp, 0, tmp.length);


       /* android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(0, info);*/
     /*   float bili=(float)width/size.height;*/

        Matrix matrix = new Matrix();
        matrix.setRotate(getOrientation(FirstActivity.this));
        bitmap = Bitmap.createBitmap(bitmap,0,0,size.width,size.height,matrix,true);
        // bitmap = Bitmap.createBitmap(bitmap,(int)(40*scale/bili),(int)(((height-(int) (width-80*scale))/2)/bili),(int) ((width-80*scale)/bili),(int) ((width-80*scale)/bili),null,true);
        //Bitmap bitmap1 = rotateBitmap(bitmap, info.orientation);
        // Log.d("eee", size.width+"   "+ size.height+"  "+(int)(40*scale/bili)+"   "+(int)(((height-(int) (width-80*scale))/2)/bili)+"   "+(int) ((width-80*scale)/bili)+"   "+(int) ((width-80*scale)/bili));
        return bitmap;
    }


    public static void setCameraDisplayOrientation(Activity activity,
                                                   int cameraId, android.hardware.Camera camera) {
        android.hardware.Camera.CameraInfo info =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break;
            case Surface.ROTATION_90: degrees = 90; break;
            case Surface.ROTATION_180: degrees = 180; break;
            case Surface.ROTATION_270: degrees = 270; break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }

    public static int getOrientation(Context context) {
        Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int rotation = display.getRotation();
        int orientation;
        boolean expectPortrait;
        switch (rotation) {
            case Surface.ROTATION_0:
            default:
                orientation = 90;
                expectPortrait = true;
                break;
            case Surface.ROTATION_90:
                orientation = 0;
                expectPortrait = false;
                break;
            case Surface.ROTATION_180:
                orientation = 270;
                expectPortrait = true;
                break;
            case Surface.ROTATION_270:
                orientation = 180;
                expectPortrait = false;
                break;
        }
        boolean isPortrait = display.getHeight() > display.getWidth();
        if (isPortrait != expectPortrait) {
            orientation = (orientation + 270) % 360;
        }
        return 0-orientation;
    }

    /* @Override
     protected void onResume() {
         super.onResume();
         mCamera = Camera.open();//open the camera for the application
     }
 */
    @Override
    protected void onPause() {
        super.onPause();
        // if you are using MediaRecorder, release it first
        // releaseCamera();              // release the camera immediately on pause event
    }



    private void releaseCamera(){
        if (mCamera != null){
            mCamera .stopPreview();
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseCamera();
    }


    public static  Camera.Size getCloselyPreSize(boolean isPortrait, int surfaceWidth, int surfaceHeight, List<Camera.Size> preSizeList) {
        int reqTmpWidth;
        int reqTmpHeight;
        // 当屏幕为垂直的时候需要把宽高值进行调换，保证宽大于高
        if (isPortrait) {
            reqTmpWidth = surfaceHeight;
            reqTmpHeight = surfaceWidth;
        } else {
            reqTmpWidth = surfaceWidth;
            reqTmpHeight = surfaceHeight;
        }
        //先查找preview中是否存在与surfaceview相同宽高的尺寸
        for(Camera.Size size : preSizeList){
            if((size.width == reqTmpWidth) && (size.height == reqTmpHeight)){
                return size;
            }
        }

        // 得到与传入的宽高比最接近的size
        float reqRatio = ((float) reqTmpWidth) / reqTmpHeight;
        float curRatio, deltaRatio;
        float deltaRatioMin = Float.MAX_VALUE;
        Camera.Size retSize = null;
        for (Camera.Size size : preSizeList) {
            curRatio = ((float) size.width) / size.height;
            deltaRatio = Math.abs(reqRatio - curRatio);
            if (deltaRatio < deltaRatioMin) {
                deltaRatioMin = deltaRatio;
                retSize = size;
            }
        }

        return retSize;
    }
}
